<?php
namespace SDXApi\Controller;
use Think\Controller;
use Think\Model;

use SDXApi\Model\UsersModel;

/**
 * 统计数据接口类
 * @author ^2_3^
 */
class StatisticsController extends Controller {
    
    //-/ 排序字段
    private $cmp_fields = '';
    //-/ 排序顺序
    private $cmp_fields_sort = 'asc';
    
    public function __construct(){
        parent::__construct();
        
//         $host_name = $_SERVER['HTTP_HOST'];
//         if( strpos(strtolower($host_name), 'shidexian.com') !== false ) {
//             C('DB_HOST', 'rm-wz97t49plsdlws69yrw.mysql.rds.aliyuncs.com');
//         }
        
        // 连接查询方式
//         $con_type = I("request.con_type", 0, "intval");
//         if( empty($con_type) ) {
// //             $config = array(
// //                 'DB_HOST'=>'sdx-ads-462ecb0a.cn-hangzhou-1.ads.aliyuncs.com',
// //                 'DB_USER'=>'LTAI2GVCj3z8eNzP',
// //                 'DB_PWD'=>'9z8CGENwamLdbjTIIfDIfRQrECClkI',
// //                 'DB_NAME'=>'sdx_ads',
// //                 'DB_PORT'=>10078,
// //             );
// //             $config = array_merge(C('DB'), $config);
// //             $this->model->config=$config;
// //             $this->model->connect();

//             C('DB_HOST', 'sdx-ads-462ecb0a.cn-hangzhou-1.ads.aliyuncs.com');
//             C('DB_USER', 'LTAI2GVCj3z8eNzP');
//             C('DB_PWD', '9z8CGENwamLdbjTIIfDIfRQrECClkI');
//             C('DB_NAME', 'sdx_ads');
//             C('DB_PORT', '10078');
        
//         } else {
//             $host_name = $_SERVER['HTTP_HOST'];
//             if( strpos(strtolower($host_name), 'w.shidexian.com') > -1 ) {
// //                 $config = array(
// //                     'DB_HOST'=>'rm-wz97t49plsdlws69yrw.mysql.rds.aliyuncs.com'
// //                 );
// //                 $config = array_merge(C('DB'), $config);
// //                 $this->model->config=$config;
// //                 $this->model->connect();
//                 C('DB_HOST', 'rm-wz97t49plsdlws69yrw.mysql.rds.aliyuncs.com');
//             }
        
//         }
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
        $date_end = I('request.date_end', '', 'trim');
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d');
            $time_start = local_strtotime( $date_start );
        }else {
            $time_start = local_strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $date_end = date('Y-m-d H:i:s');
            $time_end = local_strtotime( $date_end );
        }else {
            $time_end = local_strtotime( $date_end );
        }
        /// 过滤条件
        $where_oi = "
            oi.order_status in (1, 5)
            and oi.pay_status = 2
            and u.user_name like 'wx_196%'
        ";
        if( !empty( $time_start ) ) {
            $where_oi .= " and oi.add_time >= {$time_start} ";
        }
        if( !empty( $time_end ) ) {
            $where_oi .= " and oi.add_time < {$time_end} ";
        }
        $info_196 = M('order_info')->alias('oi')
            ->join('sdx_users u on oi.user_id = u.user_id', 'left')
            ->where( $where_oi )
            ->find();
//         if( empty($info_196) ) {
            $decimal = round(rand(1, 999)/10000, 4);
            $_REQUEST['enlarge'] = 10 + 0.1 + $decimal;
//         }
        
        header('Access-Control-Allow-Origin: *');
    }
    
    /**
     * http://apidev.cyb.cn/index.php?s=/statistics/sayhello
     */
    public function sayhello() {
        echo 'hello, ^2_3^!';
    }
    
    /**
     * [完善订单数据] 更新订单经纬度/配送区域
     * http://apidev.cyb.cn/index.php?s=/statistics/update_order_info
     * http://api.shidexian.com/index.php?s=/statistics/update_order_info
     * @author ^2_3^
     */
    public function update_order_info() {
        set_time_limit(0);
        $start = microtime(true);
        
        // 日期开始
        $date_begin_str = I('request.date_begin_str', '', 'trim');
        // 日期结束
        $date_end_str = I('request.date_end_str', '', 'trim');
        // 上次记录ID
        $last_id = I('request.last_id', 0, 'int');
        empty($last_id) && $last_id = 0;
        $uoi_lastid = S('uoi_lastid_'.$date_begin_str);
        if( empty($date_begin_str) || empty($date_end_str) || empty($last_id) ) {
            returnApiError('提示:参数缺失;');
            
        }else if( isset($uoi_lastid) && $last_id <= $uoi_lastid) {
            returnApiError('提示:数据已处理, 请进行下轮数据;');
        }
        $uoi_lastid_str = empty($uoi_lastid) ? "准备开始[{$date_begin_str}_{$date_end_str}]" : 
            "{$uoi_lastid}[{$date_begin_str}_{$date_end_str}]";
// w_log('lng_lat_region_result', $uoi_lastid_str);
        S('uoi_lastid_'.$date_begin_str, $last_id, 600);
        
        /// 读取数据
        $arr_oi = self::get_order_data($date_begin_str, $date_end_str, $last_id);
        $num = count($arr_oi);
        if( $num == 0 ) {
            returnApiError('提示:已经处理完;');
        }
        $data['num'] = $num;
        $data['num_msg'] = ("处理记录总数: {$num}");
        
        /// 循环处理(地址转经纬度[get_lng_lat]; 经纬度匹配区[UserModel/get_distribution_by_gps]); 循环更新;
        $num_fail = 0;
        $num_region_fail = 0;
        $idx = 0;
        foreach ( $arr_oi as $i_key=>$i_arr ){
            ++$idx;
            if( $idx == $num ) {
                $data['lastid'] = $i_arr['order_id'];
                $data['lastid_msg'] = ("lastid: {$i_arr['order_id']}");
            }
            
            //-/ 详细地址_处理
            $address = str_replace( array($i_arr['province_name'], $i_arr['city_name'], $i_arr['district_name']), 
                array('', '', ''), $i_arr['address']);
            
            /// 地址经度纬度
            $address = $i_arr['province_name'].$i_arr['city_name'].$i_arr['district_name'].trim($address);
            $arr_lng_lat = get_lng_lat( $address );
            if( empty($arr_lng_lat['lng']) || empty($arr_lng_lat['lat']) ) {
                ++$num_fail;
// w_log('lng_lat_log', $i_arr['order_id'].'   '.$i_arr['order_sn']);
// w_log('lng_lat_log', $address);
                continue;
            }
            
            /// 经纬度匹配区
            $m_users = new UsersModel();
            $arr_region = $m_users->get_distribution_by_gps($arr_lng_lat['lat'], $arr_lng_lat['lng']);
            if( empty($arr_region['wdr_id']) ) {
                ++$num_region_fail;
// w_log('lng_lat_region_log', $i_arr['order_id'].' '.$i_arr['order_sn'].' '.
//     $arr_lng_lat['lng'].' '.$arr_lng_lat['lat'].' '.$address);
// w_log('lng_lat_region_log', json_encode($arr_region));
// w_log('lng_lat_region_log', '--- --- ---');
                continue;
            }
            
            /// 更新订单数据;
            $where_oi_u = "
                referer = '专场'
                AND wdr_id = 0
                AND order_id = {$i_arr['order_id']}
            ";
            $data_oi_u = array(
                "wdr_id" => $arr_region['wdr_id'],
                "longitude" => $arr_lng_lat['lng'],
                "latitude" => $arr_lng_lat['lat']
            );
            $flag_u = M('order_info')->where( $where_oi_u )->save( $data_oi_u );
// w_log( 'lng_lat_oi_log', $i_arr['order_id'].'   '.$i_arr['order_sn'] );
        }
        
        $num_ok = $num - $num_fail;
        $data['num_ok'] = $num_ok;
        $data['num_ok_msg'] = "经纬度转换成功: {$num_ok}";
        $data['num_fail'] = $num_fail;
        $data['num_fail_msg'] = "经纬度转换失败: {$num_fail}";
        
        $data['num_region_fail'] = $num_region_fail;
        $data['num_region_fail_msg'] = "经纬度转配送区失败: {$num_region_fail}";
        $num_region_ok = $num_ok - $num_region_fail;
        $data['num_region_ok'] = $num_region_ok;
        $data['num_region_ok_msg'] = "经纬度转配送区成功: {$num_region_ok}";
        
        $end = microtime(true);
        $time = $end - $start;
        $data['time'] = $time;
// w_log('lng_lat_region_result', json_encode($data));
        returnApiSuccess($data, 'ok');
    }
    
    /**
     * [完善订单数据]获取订单数据
     * @param string $date_begin_str
     * @param string $date_end_str
     * @return array $arr_oi
     * @author ^2_3^
     */
    private function get_order_data( $date_begin_str = '2017-07-01', $date_end_str = '2017-08-01', $last_id = 0 ) {
        $arr_oi = array();
        
        $where_oi = "
            oi.pay_status >= 2
        	AND oi.order_status IN (1, 5)
        	AND oi.shipping_status = 2
        	AND u.user_name LIKE 'wx_196%'
        	AND oi.referer = '专场'
        	AND oi.add_time >= (UNIX_TIMESTAMP('{$date_begin_str}') - 8 * 3600)
        	AND oi.add_time < (UNIX_TIMESTAMP('{$date_end_str}') - 8 * 3600)
        	AND oi.wdr_id = 0
        ";
        if( !empty($last_id) ) {
            $where_oi = "{$where_oi} AND oi.order_id > {$last_id}";
        }
        $arr_oi = M('order_info oi')
            ->field('
                oi.order_id,
            	oi.order_sn,
            	oi.country,
            	oi.province,
            	rp.region_name AS province_name,
            	oi.city,
            	rc.region_name AS city_name,
            	oi.district,
            	rd.region_name AS district_name,
            	oi.address,
            	oi.wdr_id,
            	oi.longitude,
            	oi.latitude
            ')
            ->join('sdx_users u ON u.user_id = oi.user_id', 'left')
            ->join('sdx_region rp ON rp.region_id = oi.province', 'left')
            ->join('sdx_region rc ON rc.region_id = oi.city', 'left')
            ->join('sdx_region rd ON rd.region_id = oi.district', 'left')
            ->where( $where_oi )
            ->limit('0, 1000')
            ->select();
        $str_sql = M()->getLastSql();
// w_log('sql_log', "{$date_begin_str}_{$date_end_str}");
// w_log('sql_log', $str_sql);
        
        return $arr_oi;
        /*
         SELECT
        	oi.order_id,
        	oi.order_sn,
        	oi.country,
        	oi.province,
        	rp.region_name AS province_name,
        	oi.city,
        	rc.region_name AS city_name,
        	oi.district,
        	rd.region_name AS district_name,
        	oi.address,
        	oi.referer,
        	oi.wdr_id,
        	oi.longitude,
        	oi.latitude
        FROM
        	sdx_order_info oi
        LEFT JOIN sdx_users u ON u.user_id = oi.user_id
        LEFT JOIN sdx_region rp ON rp.region_id = oi.province
        LEFT JOIN sdx_region rc ON rc.region_id = oi.city
        LEFT JOIN sdx_region rd ON rd.region_id = oi.district
        WHERE
        	oi.pay_status >= 2
        	AND oi.order_status IN (1, 5)
        	AND oi.shipping_status = 2
        	AND u.user_name LIKE 'wx_196%'
        	AND oi.referer = '专场'
        	AND oi.add_time >= (UNIX_TIMESTAMP('2017-07-01') - 8 * 3600)
        	AND oi.add_time < (UNIX_TIMESTAMP('2017-08-01') - 8 * 3600)
        	AND oi.wdr_id = 0 
         */
    }
    
    /**
     * 下载Excel表格
     * http://apidev.cyb.cn/index.php?s=/statistics/get_data4excel/month/2017-08
     * http://api.shidexian.com/index.php?s=/statistics/get_data4excel/month/2017-08
     */
    public function get_data4excel() {
        set_time_limit(0);
        
        /// 提取数据月份
        $month = I('request.month', '', 'trim');
        $date_begin = I('request.date_begin', '', 'trim');
        $date_end = I('request.date_end', '', 'trim');
        
        import('Vendor.PHPExcel.PHPExcel');
        import('Vendor.PHPExcel.PHPExcel.Reader.Excel5');
        import('Vendor.PHPExcel.PHPExcel.IOFactory');
        
        $objPHPExcel = new \PHPExcel();
        
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(5);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        
        $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1','order_sn')
        ->setCellValue('B1','goods_amount')
        ->setCellValue('C1','consignee')
        ->setCellValue('D1','address')
        ->setCellValue('E1','mobile')
        ->setCellValue('F1','referer')
        ->setCellValue('G1','add_date')
        ->setCellValue('H1','goods_name')
        ->setCellValue('I1','goods_price')
        ->setCellValue('J1','goods_number')
        ->setCellValue('K1','shipping_exman_name')
        ->setCellValue('L1','shipping_exman_mobile');
        
        
//         $date_str = "{$month}-01";
        
//         $date_begin = date('Y-m-d', strtotime($date_str));
//         $month_bstr = $month_tmp = date('Y-m', strtotime($date_begin));
//         $month_estr = date('Y-m', strtotime("$date_begin +1 month"));
        
//         $date_end = date('Y-m-d', strtotime($date_begin)+86400);

        $date_begin_str = $date_begin;
        $date_end_str = $date_end;
        
        $date_end = date('Y-m-d', strtotime($date_begin)+86400);
        
        $idx = 1;
        $num = 1;
//         while ( $month_tmp != $month_estr && $idx < 32 ){
        while ( $date_begin != $date_end_str && $idx < 32 ){
// w_log('cyb_log', "{$date_begin}_{$date_end}_{$date_end_str}");
            $arr = self::get_arr_info($date_begin, $date_end);
            
//             $date_begin = date('Y-m-d', strtotime($date_end));
//             $month_tmp = date('Y-m', strtotime($date_begin));
//             $date_end = date('Y-m-d', strtotime($date_begin)+86400);

            $date_begin = date('Y-m-d', strtotime($date_end));
            $date_end = date('Y-m-d', strtotime($date_begin)+86400);
            
            $idx += 1;
            
            foreach ($arr['result'] as $k => $v) {
                ++$num;
                
                $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A' . $num, $v['order_sn'])
                ->setCellValue('B' . $num, $v['goods_amount'])
                ->setCellValue('C' . $num, $v['consignee'])
                ->setCellValue('D' . $num, $v['address'])
                ->setCellValue('E' . $num, $v['mobile'])
                ->setCellValue('F' . $num, $v['referer'])
                ->setCellValue('G' . $num, $v['add_date'])
                ->setCellValue('H' . $num, $v['goods_name'])
                ->setCellValue('I' . $num, $v['goods_price'])
                ->setCellValue('J' . $num, $v['goods_number'])
                ->setCellValue('K' . $num, $v['shipping_exman_name'])
                ->setCellValue('L' . $num, $v['shipping_exman_mobile']);
            }
        }
        
        $objPHPExcel->getActiveSheet()->setTitle( "{$month}订单数据" );
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
//         header("Content-Disposition: attachment;filename=shidexian({$month_bstr}订单).xls");
        header("Content-Disposition: attachment;filename=shidexian({$date_begin_str}_{$date_end_str}订单).xls");
        header('Cache-Control: max-age=0');
        $write = new \PHPExcel_Writer_Excel5($objPHPExcel);
        $write->save('php://output');

    }
    
    /**
     * 获取订单数据
     * @param string $bdate 开始日期;
     * @param string $edate 结束日期;
     * @return array arr_result 结果数据;
     *  arr_result['title'] Excel标题;
     *  arr_result['result'] 查询结果集;
     *  arr_result['fields'] Excel表头标题(字段英文名称);
     *  arr_result['sql'] 查询语句;
     */
    private function get_arr_info($bdate='2017-08-01', $edate='2017-08-02') {
        $arr_result = array();
        
        $arr_result['title'] = "订单数据";
        
        $arr_result['fields'] = array(
            'order_sn' => '25',
            'goods_amount' => '25',
            'consignee' => '25',
            'address' => '25',
            'mobile' => '25',
            'referer' => '25',
            'add_date' => '25',
            'goods_name' => '25',
            'goods_price' => '25',
            'goods_number' => '25',
            'shipping_exman_name' => '25',
            'shipping_exman_mobile' => '25'
        );
        
        /* $sql = "
            SELECT
            	tmp_oi.order_sn,
            	tmp_oi.goods_amount,
            	tmp_oi.consignee,
            	tmp_oi.address,
            	tmp_oi.mobile,
            	tmp_oi.referer,
            	tmp_oi.add_date,
            	og.goods_name,
            	(og.goods_price + og.bonus_price) AS goods_price,
            	og.goods_number,
            	tmp_oi.shipping_exman_name,
            	tmp_oi.shipping_exman_mobile
            FROM
            (
            	SELECT
            		oi.order_id,
            		CONCAT('`', oi.order_sn) AS order_sn,
            		oi.goods_amount,
            		oi.consignee,
            		oi.address,
            		oi.mobile,
            		oi.referer,
            		FROM_UNIXTIME(oi.add_time+28800) AS add_date,
            		oi.shipping_exman_name,
            		oi.shipping_exman_mobile
            	FROM
            		sdx_order_info oi
            	WHERE oi.pay_time >= (UNIX_TIMESTAMP('{$bdate}')-28800)
            		AND oi.pay_time < (UNIX_TIMESTAMP('{$edate}')-28800)
            		AND oi.mobile != ''
            		-- AND oi.shipping_extend_type != ''
            		AND oi.order_status IN (1, 5)
            		AND oi.pay_status IN (2)
            		AND oi.shipping_status = 2
            		AND oi.referer NOT IN ('891', '门店')
            --	LIMIT 0, 100
            ) tmp_oi
            INNER JOIN sdx_order_goods og ON tmp_oi.order_id = og.order_id
        "; */
        $sql = "
            SELECT
                tmp_oi.order_sn,
                tmp_oi.goods_amount,
                tmp_oi.consignee,
                tmp_oi.address,
                tmp_oi.mobile,
                tmp_oi.referer,
                tmp_oi.add_date,
                og.goods_name,
                (og.goods_price + og.bonus_price) AS goods_price,
                og.goods_number,
                tmp_oi.shipping_exman_name,
                tmp_oi.shipping_exman_mobile
            FROM
            (
                SELECT
                    oi.order_id,
                    CONCAT('`', oi.order_sn) AS order_sn,
                    oi.goods_amount,
                    oi.consignee,
                    oi.address,
                    oi.mobile,
                    oi.referer,
                    FROM_UNIXTIME(oi.add_time+28800) AS add_date,
                    oi.shipping_exman_name,
                    oi.shipping_exman_mobile
                FROM
                    sdx_order_info oi
                WHERE oi.pay_time >= (UNIX_TIMESTAMP('{$bdate}')-28800)
                    AND oi.pay_time < (UNIX_TIMESTAMP('{$edate}')-28800)
                    AND oi.mobile != ''
                    AND oi.order_status IN (1, 5)
                    AND oi.pay_status IN (2)
                    AND oi.shipping_status = 2
                    AND oi.referer NOT IN ('891', '门店')
            ) tmp_oi
            INNER JOIN sdx_order_goods og ON tmp_oi.order_id = og.order_id
        ";
// w_log('cyb_log', $sql);
        $arr_result['sql'] = $sql;
        
        $arr = M()->query($sql);
        $arr_result['result'] = $arr;
        
        return $arr_result;
    }
    
/// DBO_运营实时数据_START ///
// 参数: date_start 开始日期;
// 参数: date_end 结束日期, 为空则为当前日期时间;
// 参数: enlarge 放大倍数, 默认5倍;
    
    /**
     * [运营实时数据] 获取累计访问量(浏览量)
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_get_page_vtimes/
     **需求
     * 累计访问量：当日0点，到现在时间点的页面浏览量，不做去重处理[用户页面浏览行为表(sdx_user_behavior_browse)];
     *
     * @author ^2_3^
     */
    public function dbo_get_page_vtimes() {
        set_time_limit(0);
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = "empty data;";
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
        $date_end = I('request.date_end', '', 'trim');
        $enlarge = I('request.enlarge', 1, 'trim');
        
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d');
            $time_start = strtotime( $date_start );
        }else {
            $time_start = strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $time_end = time();
        }else {
            $time_end = strtotime( $date_end );
        }
        empty($enlarge) && $enlarge = 1;
        
        //-/ 用户页面浏览行为表(sdx_user_behavior_browse)
        /*
         page_id
         1.进入专题页; 2.分类页; 3.我要充值; 4.金额变动记录; 6.购物车页; 7.设置页; 8.客服页; 9.消息页面;
         10.首页; 11.我的收货地址; 12.编辑地址; 13.搜索收货地址页面; 14.新增地址页面; 15.去换购页面;
         16.提交订单页面（去结算）; 17.我的; 18.我的评价; 19.我的红包; 20.手机绑定; 21.修改支付密码;
         22.专辑页面; 23.(地图)搜索地址; 24.点击账户充值; 29.点击卡券充值; 32.浏览搜索页面;
         */
        $where_ubb = '';
        if( !empty($time_start) ) {
            $where_ubb .= " ubb.add_time >= {$time_start} AND ";
        }
        if( !empty($time_end) ) {
            $where_ubb .= " ubb.add_time < {$time_end} AND ";
        }
        $where_ubb .= " ubb.page_id IN (1,2,3,4,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,29,32) ";
        
        $count_ubb_ids = M('user_behavior_browse ubb')->where( $where_ubb )->count(id);
// w_log('cyb_log', "dbo_get_page_vtimes ".M()->getLastSql());
        
        if( !empty($count_ubb_ids) ) {
            $data['status'] = 1;
            $data['msg'] = 'ok';
        }else {
            $count_ubb_ids = 0;
        }
        $data['count_ubb_ids'] = round($count_ubb_ids * $enlarge);
        $data['count_ubb_ids_ori'] = $count_ubb_ids;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
    /**
     * [运营实时数据] 获取登录相关信息
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_get_login_info/
     **需求
     * 同时在线人数：统计前20分钟登录人数累积量，例如当前时间为13:20，统计的是13:00~13:20的登录用户统计量;
     * APP比例：当日, 安卓苹果移动端登录用户数占当日登录总数的比例;
     * 微信比例：当日, 使用微信公众号登录微店的用户数占登录总数的比例;
     * 男女比例：当日登录用户中男女各自所占的比例;
     * 
     * @author ^2_3^
     */
    public function dbo_get_login_info() {
        set_time_limit(0);
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = "empty data;";
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
        $date_end = I('request.date_end', '', 'trim');
        $enlarge = I('request.enlarge', 1, 'trim');
        
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d H:i:s', time()-1200);
            $time_start = strtotime( $date_start );
        }else {
            $time_start = strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $date_end = date('Y-m-d H:i:s');
            $time_end = strtotime( $date_end );
        }
        empty($enlarge) && $enlarge = 1;
    
        $where_uba = '';
        if( !empty($time_start) ) {
            $where_uba .= " uba.add_time >= {$time_start} AND ";
        }
        if( !empty($time_start) ) {
            $where_uba .= " uba.add_time < {$time_end} AND ";
        }
        $where_uba .= ' uba.type = "login" AND uba.type_id = 0 ';
        
        $list_uba = M('user_behavior_address uba')
            ->field('
                uba.source,	
                COUNT( uba.id ) AS count_uba_id
            ')
            ->where( $where_uba )
            ->group('uba.source')
            ->select();
// w_log('cyb_log', "dbo_get_login_info[source] ".M()->getLastSql());

        /// 登录设备(APP/wx)类型
        $count_ids = 0;
        $count_app_ids = 0;
        $count_wx_ids = 0;
        foreach ( $list_uba as $l_key=>$l_arr ){
            $count_ids += $l_arr['count_uba_id'];
            
            if( $l_arr['source'] == 'android' || $l_arr['source'] == 'ios' ) {
                $count_app_ids += $l_arr['count_uba_id'];
                
            }else {
                $count_wx_ids += $l_arr['count_uba_id'];
            }
        }
        
        /// 男女比例
        $list_uba_sex = M('user_behavior_address uba')
            ->join(' sdx_wechat_user wu ON wu.ect_uid = uba.uid ', 'LEFT')
            ->field('
                wu.sex,
                COUNT(uba.id) AS count_uba_id
            ')
            ->where( $where_uba )
            ->group('wu.sex')
            ->select();
// w_log('cyb_log', "dbo_get_login_info[sex] ".M()->getLastSql());
        //-/ 列表处理
        $sex_male = 0;
        $sex_female = 0;
        foreach ( $list_uba_sex as $s_key=>$s_arr ){
            if( $s_arr['sex'] == 1 ) {
                $sex_male += $s_arr['count_uba_id'];
                
            }else {
                $sex_female += $s_arr['count_uba_id'];
            }
        }
        
        if( !empty($list_uba) ) {
            $data['status'] = 1;
            $data['msg'] = 'ok';
        }
        $data['count_ids'] = round($count_ids * $enlarge);
        $data['count_app_ids'] = round($count_app_ids * $enlarge);
        $data['count_wx_ids'] = round($count_wx_ids * $enlarge);
        $data['per_app'] = empty( $data['count_ids'] ) ? 0 : 
            round($data['count_app_ids']/$data['count_ids'], 3) * 100;
        $data['per_wx'] = empty( $data['count_ids'] ) ? 0 : 
            round($data['count_wx_ids']/$data['count_ids'], 3) * 100;
        
        $data['count_ids_ori'] = $count_ids;
        $data['count_app_ids_ori'] = $count_app_ids;
        $data['count_wx_ids_ori'] = $count_wx_ids;
        $data['per_app_ori'] = empty( $count_ids ) ? 0 : round($count_app_ids / $count_ids, 3) * 100;
        $data['per_wx_ori'] = empty( $count_ids ) ? 0 : round($count_wx_ids / $count_ids, 3) * 100;
        
        $data['sex_male'] = round($sex_male * $enlarge);
        $data['sex_female'] = round($sex_female * $enlarge);
        $data['per_male'] = empty( $data['count_ids'] ) ? 0 : round($data['sex_male']/$data['count_ids'], 3) * 100;
        $data['per_female'] = empty( $data['count_ids'] ) ? 0 : round($data['sex_female']/$data['count_ids'], 3) * 100;
        
        $data['sex_male_ori'] = $sex_male;
        $data['sex_female_ori'] = $sex_female;
        $data['per_male_ori'] = empty( $count_ids ) ? 0 : round( $sex_male/$count_ids, 3) * 100;
        $data['per_female_ori'] = empty( $count_ids ) ? 0 : round( $sex_female/$count_ids, 3) * 100;

        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
    /**
     * [运营实时数据] 获取销售情况
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_get_sales_info/
     **需求
     * 当天销售额: 当日0时到目前为止的交易总额不要剔除退款和取消订单;
     * 订单总数: 当日0时到目前为止的交易总订单数，不要剔除退款和取消订单;
     * 线上订单量: 当日0时到目前为止，配送到家和到店自提的订单总量;
     * 线下订单量: 当日0时到目前为止，收银机收银的订单量;
     *
     * 待发货订单量：当日0时到目前为止，物流状态处于未配货、配货中、发货中的订单量统计,过滤已出仓订单;
     * 预警订单量[舍弃]：当日0时到目前为止，客服工作中，问题单的统计量;
     * 预警订单量：当日0时到目前为止，客服工作中，客服工单订单量;
     * 
     * @author ^2_3^
     */
    public function dbo_get_sales_info() {
        set_time_limit(0);
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = "empty data;";
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
        $date_end = I('request.date_end', '', 'trim');
        $enlarge = I('request.enlarge', 0, 'trim');
        
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d');
            $time_start = local_strtotime( $date_start );
        }else {
            $time_start = local_strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $date_end = date('Y-m-d H:i:s');
            $time_end = local_strtotime( $date_end );
        }else {
            $time_end = local_strtotime( $date_end );
        }
        empty($enlarge) && $enlarge = 1;
        
        $where_oi = '';
        if( !empty( $time_start ) ) {
            !empty( $where_oi ) && $where_oi .= " AND ";
            $where_oi .= " oi.add_time >= {$time_start} ";
        }
        if( !empty( $time_end ) ) {
            !empty( $where_oi ) && $where_oi .= " AND ";
            $where_oi .= " oi.add_time < {$time_end} ";
        }
        
        /// 订单数量/商品金额
        $list_oi = M('order_info oi')
            ->field('
                oi.referer,
            	COUNT(oi.order_id) AS count_oid,
            	SUM(oi.goods_amount) AS sum_goods_amount
            ')
            ->where( $where_oi )
            ->group( 'oi.referer' )
            ->select();
// w_log('cyb_log', "dbo_get_sales_amount[订单数量/商品金额] ".M()->getLastSql());
        //-/ 列表处理
        $sum_goods_amount = 0;
        $count_oid = 0;
        $count_oid_online = 0;
        $count_oid_offline = 0;
        foreach ( $list_oi as $l_key=>$l_arr ){
            $sum_goods_amount += $l_arr['sum_goods_amount'];
            $count_oid += $l_arr['count_oid'];
            
            if( $l_arr['referer'] == '891' || $l_arr['referer'] == '门店' ) {
                $count_oid_offline += $l_arr['count_oid'];
                
            }else {
                $count_oid_online += $l_arr['count_oid'];
            }
        }
        
        /// 待发货订单量：当日0时到目前为止，物流状态处于未配货、配货中、发货中的订单量统计;
        $where_oi .= ' AND oi.shipping_status IN (0, 3, 5) AND oi.outgo = 0 ';
        $count_oid_do = M('order_info oi')
            ->where( $where_oi )
            ->count('oi.order_id');
// w_log('cyb_log', "dbo_get_sales_amount[待发货订单量] ".M()->getLastSql());
        $data['count_oid_do'] = round($count_oid_do * $enlarge);
        $data['count_oid_do_ori'] = $count_oid_do;
        
        /// 预警订单量[舍弃]：当日0时到目前为止，客服工作中，问题单的统计量;
//         $where_al = '';
//         if( !empty($time_start) ) {
//             $where_al .= " al.trigger_time >= {$time_start} AND ";
//         }
//         if( !empty($time_end) ) {
//             $where_al .= " al.trigger_time < {$time_end} AND ";
//         }
//         $where_al .= ' al.type = 6 ';
//         //-/ 预警订单量
//         $count_warning = M('alarm_log2 al')
//             ->where( $where_al )
//             ->count( 'order_sn' );

        /// 预警订单量：当日0时到目前为止，客服工作中，客服工单订单量;
        $where_osw = '';
        if( !empty($time_start) ) {
            $where_osw .= " osw.add_time >= {$time_start} AND ";
        }
        if( !empty($time_end) ) {
            $where_osw .= " osw.add_time < {$time_end} AND ";
        }
        $where_osw .= " osw.state = 1 ";
        //-/ 客服工单
        $count_warning = M('order_service_work osw')
            ->where( $where_osw )
            ->count( 'osw.id' );
// w_log('cyb_log', "dbo_get_sales_amount[预警订单量] ".M()->getLastSql());
        $data['count_warning'] = round($count_warning * $enlarge);
        $data['count_warning_ori'] = $count_warning;

        if( !empty( $list_oi ) ) {
            $data['status'] = 1;
            $data['msg'] = 'ok';
        }else {
            $sum_goods_amount = 0;
        }
        $data['sum_goods_amount'] = round($sum_goods_amount * $enlarge, 2);
        $data['sum_goods_amount_ori'] = $sum_goods_amount;
        
        $data['count_oid'] = round($count_oid * $enlarge);
        $data['count_oid_ori'] = $count_oid;
        
        $data['count_oid_online'] = round($count_oid_online * $enlarge);
        $data['count_oid_online_ori'] = $count_oid_online;
        
        $data['count_oid_offline'] = round($count_oid_offline * $enlarge);
        $data['count_oid_offline_ori'] = $count_oid_offline;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
    /**
     * [运营实时数据] 商品分类销量
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_get_gtype_info/
     * 
     * @author ^2_3^
     */
    public function dbo_get_gtype_info() {
        set_time_limit(0);
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = "empty data;";
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
// $date_start = '2017-07-01';
        $date_end = I('request.date_end', '', 'trim');
        $enlarge = I('request.enlarge', 0, 'trim');
        
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d');
            $time_start = local_strtotime( $date_start );
        }else {
            $time_start = local_strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $date_end = date('Y-m-d H:i:s');
            $time_end = local_strtotime( $date_end );
        }else {
            $time_end = local_strtotime( $date_end );
        }
        empty($enlarge) && $enlarge = 1;
        
        /// 商品分类销量
        $where_g = '';
        if( !empty($time_start) ) {
            $where_g .= " oi.add_time >= {$time_start} AND ";
        }
        if( !empty($time_end) ) {
            $where_g .= " oi.add_time < {$time_end} AND ";
        }
        $where_g .= ' g.cat_id IS NOT NULL ';
        
        $list_g = M('order_info oi')
            ->field('
                g.cat_id,
                SUM(og.goods_number) AS sum_goods_number
            ')
            ->join('sdx_order_goods og ON og.order_id = oi.order_id', 'LEFT')
            ->join('sdx_goods g ON g.goods_id = og.goods_id', 'LEFT')
            ->where( $where_g )
            ->group( 'g.cat_id' )
            ->select();
// w_log('cyb_log', '商品分类销量 '.M()->getLastSql());
        
        /// 顶级菜单
        $arr_cgy = self::get_category_group();
        $arr_cname = self::get_cat_names();
        
        /// 统计处理
        $count_nums = 0;
        $arr_cat_nums = array();
        foreach ( $list_g as $l_key=>$l_arr ){
            $count_nums += $l_arr['sum_goods_number'];
            
            foreach ( $arr_cgy as $c_key=>$c_arr ){
                
                if( in_array($l_arr['cat_id'], $c_arr) ) {
                    $arr_cat_nums["c_{$c_key}"]['cat_id'] = $c_key;
                    $arr_cat_nums["c_{$c_key}"]['nums'] += $l_arr['sum_goods_number'];
                    break;
                    
                } else if( $l_arr['cat_id'] == 0 ) {
                    $arr_cat_nums["c_0"]['cat_id'] = 0;
                    $arr_cat_nums["c_0"]['nums'] += $l_arr['sum_goods_number'];
                    break;
                }
            }
        }
        
        $data['count_nums'] = round($count_nums * $enlarge);
        $data['count_nums_ori'] = $count_nums;
        
        /// 分类占比
        foreach ( $arr_cat_nums as $n_key=>$n_arr ) {
            if( $n_arr['cat_id'] == 0 ) {
                $cat_name = '散装';
            }else {
                $cat_name = $arr_cname[ $n_arr['cat_id'] ];
            }
            $arr_cat_nums[ $n_key ]['cat_name'] = $cat_name;
            
            //-/ 占比
            $per_nums = empty( $data['count_nums'] ) ? 0 : 
                round( round($n_arr['nums']*$enlarge)/$data['count_nums'], 2) * 100;
            $arr_cat_nums[ $n_key ]['per_nums'] = $per_nums;
            $per_nums_ori = empty( $data['count_nums_ori'] ) ? 0 : round( $n_arr['nums']/$data['count_nums_ori'], 2) * 100;
            $arr_cat_nums[ $n_key ]['per_nums_ori'] = $per_nums_ori;
        }
        
        if( !empty($arr_cat_nums) ) {
            $data['status'] = 1;
            $data['msg'] = 'ok';
        }

        $this->cmp_fields = 'nums';
        $this->cmp_fields_sort = 'desc';
        uasort($arr_cat_nums, "self::twodimension_arr_cmp");
        $data['arr_cat_nums'] = $arr_cat_nums;
        $data['show'] = 7;
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
    /**
     * 获取商品分类名称数组
     * @license
     *
     * @author ^2_3^
     */
    private function get_cat_names() {
        $cat_names = array();
        
        $list = M('category c')->field('c.cat_id, c.cat_name, c.parent_id')->order('c.sort_order')->select();
        foreach ($list as $key=>$arr) {
            $cat_names[ $arr['cat_id'] ] = $arr['cat_name'];
        }
    
        return $cat_names;
    }
    
    /**
     * 获取子级商品分类分组
     * @license
     *
     * @author ^2_3^
     */
    private function get_category_group( $parent_id = 0 ) {
        $catid_arr = array();

        $list = M('category c')
            ->field('
                c.cat_id, 
                c.cat_name, 
                c.parent_id
            ')
            ->order('c.sort_order')
            ->select();
    
        foreach ( $list as $key=>$carr ){
            if( $carr['parent_id'] == $parent_id ) {
                $catid_str = self::get_category_idstr($list, $carr['cat_id']);
                if( !empty($catid_str) ){
                    $catid_str = rtrim($catid_str, ',');
                    $catid_arr[ $carr['cat_id'] ] = explode(',', "{$carr['cat_id']},".$catid_str);
                }else {
                    $catid_arr[ $carr['cat_id'] ] = explode(',', "{$carr['cat_id']}");
                }
            }
        }
    
        return $catid_arr;
    }
    
    /**
     * 获取子分类字串
     *
     * @param array $cat_list 分类列表;
     * @param array $parent_id 分类父级ID;
     * @author ^2_3^
     */
    private function get_category_idstr($cat_list = array(), $parent_id = 0) {
        $catid_str = "";
    
        foreach ($cat_list as $key=>$carr){
            if( $carr['parent_id'] == $parent_id ) {
                $catid_str .= "{$carr['cat_id']},";
    
                $cat_subid_str = self::get_category_idstr($cat_list, $carr['cat_id']);
                if( !empty( $cat_subid_str ) ) {
                    $catid_str .= $cat_subid_str;
                }
            }
        }
    
        return $catid_str;
    }
    
    /**
     * [运营实时数据] 区域订单量
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_get_order_region/
     * 
     * @author ^2_3^
     */
    public function dbo_get_order_region() {
        set_time_limit(0);
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = "empty data;";
        
        /// 参数获取
        $date_start = I('request.date_start', '', 'trim');
// $date_start = '2017-07-01';
        $date_end = I('request.date_end', '', 'trim');
        $enlarge = I('request.enlarge', 0, 'trim');
        
        /// 参数处理
        if( empty( $date_start ) ) {
            $date_start = date('Y-m-d');
            $time_start = local_strtotime( $date_start );
        }else {
            $time_start = local_strtotime( $date_start );
        }
        if( empty( $date_end ) ) {
            $date_end = date('Y-m-d H:i:s');
            $time_end = local_strtotime( $date_end );
        }else {
            $time_end = local_strtotime( $date_end );
        }
        empty($enlarge) && $enlarge = 1;
        
        $where_oi = '';
        if( !empty($time_start) ) {
            $where_oi .= " oi.add_time >= {$time_start} AND ";
        }
        if( !empty($time_end) ) {
            $where_oi .= " oi.add_time < {$time_end} AND ";
        }
        $where_oi .= ' oi.district != 0 ';
        
        /// 订单总量
        $count_oid = M('order_info oi')
            ->where( $where_oi )
            ->count('oi.order_id');
        $data['count_oid'] = round($count_oid * $enlarge);
        $data['count_oid_ori'] = $count_oid;
        
        /// 区域订单
        $list_oi = M('order_info oi')
            ->field('
                oi.district,
            	r.region_name,
            	COUNT(oi.order_id) AS count_oid
            ')
            ->join('sdx_region r ON r.region_id = oi.district', 'LEFT')
            ->where( $where_oi )
            ->group('oi.district')
            ->select();
// w_log('cyb_log', '区域订单量 '.M()->getLastSql());

        /// 区域占比
        $arr_oi = array();
        foreach ( $list_oi as $l_key=>$l_arr ){
            $l_count_oid = $l_arr['count_oid'];
            $list_oi[$l_key]['count_oid'] = $l_count_oid * $enlarge;
            $list_oi[$l_key]['count_oid_ori'] = $l_count_oid;
            
            $list_oi[$l_key]['per'] = empty($data['count_oid']) ? 0 : 
                round( round($l_count_oid*$enlarge)/$data['count_oid'], 2) * 100;
            $list_oi[$l_key]['per_ori'] = empty($count_oid) ? 0 : round( $l_count_oid/$count_oid, 2) * 100;
            
            $arr_oi["idx_{$l_key}"] = $list_oi[$l_key];
        }
        
        if( !empty($list_oi) ) {
            $data['status'] = 1;
            $data['msg'] = 'ok';
        }
        $this->cmp_fields = 'count_oid';
        $this->cmp_fields_sort = 'desc';
        uasort($arr_oi, "self::twodimension_arr_cmp");
        $data['list'] = $arr_oi;
        $data['show'] = 7;
        
        /// 是否刷新前端页面
        $flag_switch = S('flag_switch');
        if( $flag_switch ) {
            $data['refresh'] = 1;
        }else {
            $data['refresh'] = 0;
        }
        
        $data['enlarge'] = $enlarge;
        $data['request'] = $_REQUEST;
        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
    /**
     * DBO_页面刷新开关
     * http://apidev.cyb.cn/index.php?s=/statistics/dbo_page_refresh_switch/switch/off
     * 
     * @param string $switch 刷新开关, off关; on开;
     * 
     * @author ^2_3^
     */
    public function dbo_page_refresh_switch() {
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = 'error';
        
        // 刷新开关
        $switch = I('request.switch', 'off', 'trim');
        if( empty($switch) || !in_array($switch, array('off', on)) ) {
            $data['msg'] = '无效请求;';
            exit( json_encode($data) );
        }
        
        /// 刷新缓存标识
        if( $switch == 'on' ) {
            S('flag_switch', 1, 300);
        }else {
            S('flag_switch', null);
        }
        $data['status'] = 1;
        $data['msg'] = "{$switch}_ok";
        
        $end = microtime(true);
        $data['time'] = $end - $start;
        exit( json_encode($data) );
    }
    
/// DBO_运营实时数据_END ///
    
    /**
     * [AJAX]获取<配送区域图>经纬度
     * http://apidev.cyb.cn/index.php?s=/statistics/map_zoning_data/
     * 
     * @param integer $wdr_id 配送小区ID;
     *
     * @author ^2_3^
     */
    public function map_zoning_data() {
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = 'error';
        
        $wdr_id = I('request.wdr_id', 0, 'intval');
        if( !IS_POST ) {
            $data['msg'] = 'error request';
            exit( json_encode($data) );
        }
        
        $where = '';
        if( !empty($wdr_id) ) {
            $where .= " AND r.id = {$wdr_id}";
        }
        
        /// 配送经纬
        $sql = "
            SELECT
            	rc.longitude,
            	rc.latitude,
            	rc.rid,
            	r.wdtype
            FROM
            	sdx_warehouse_deliver_region_coordinates AS rc,
            	sdx_warehouse_deliver_region AS r
            WHERE
            	rc.rid = r.id
                AND r. STATUS = 1 {$where}
        ";
        $data['sql'] = $sql;
        $list = M()->query( $sql );
        
        /// 配送颜色
        $dis_mode_list = S('distribution_mode_data');
        if(!$dis_mode_list){
            $dis_mode_list = M("distribution_mode")->where(array("state"=>0))->select();
            if($dis_mode_list){
                S('distribution_mode_data', $dis_mode_list);
            }
        }
        
        if( !empty($list) ) {
            $zoning_coordinates = array();
            
            foreach ( $list as $key=>$val ) {
                $zoning_coordinates[ $val['rid'] ][] = array(
                    "longitude" => $val['longitude'],
                    "latitude" => $val['latitude'],
                    "wdtype" => $val['wdtype']
                );
            }
            
            $data['status'] = 1;
            $data['msg'] = "ok";
            $data['zoning'] = $zoning_coordinates;
            $data['dis_mode_list'] = $dis_mode_list;
        
        }else {
            $data['msg'] = 'empt data';
        }
        
        $end = microtime(true);
        $time = $end - $start;
        $data['time'] = $time;
        exit( json_encode($data) );
    }
    
    /**
     * [AJAX]地图_获取<用户登录闪烁图>数据
     * http://apidev.cyb.cn/index.php?s=/Statistics/map_user_login_data/
     * @author ^2_3^
     */
    public function map_user_login_data() {
        $data = array();
        
        // 结束时间
        $end_date = date('Y-m-d', time());
        $e_time = strtotime($end_date);
        // 开始时间
        $s_time = $e_time - 29 * 86400;
        $start_date = date("Y-m-d", $s_time);
        
        /// 参数处理
        $utype = I('request.utype', '', 'trim');
        
        /// 过滤条件
        $where = '';
        if( !empty($start_date) ){
            $start_time = strtotime($start_date);
            $where .= " AND uba.add_time >= {$start_time} ";
        }
        if( !empty($end_date) ) {
            $end_time = strtotime( $end_date ) + 86400;
            $where .= " AND uba.add_time < {$end_time} ";
        }
        
        if( empty($utype) || !in_array($utype, array('ios', 'android', 'h5')) ) {
            exit( json_encode( $data ) );
        }
        
        $sql = "
            SELECT
                longitude,
                latitude,
                COUNT(0) AS count_num
            FROM
                sdx_user_behavior_address uba
            WHERE
                uba.type = 'login'
                AND source = '{$utype}' {$where}
            GROUP BY CONCAT(longitude, '_', latitude)
        ";
        $list = M()->query( $sql );
        
        foreach ( $list as $key=>$arr ){
            $data[] = array( floatval($arr['longitude']), floatval($arr['latitude']), intval($arr['count_num']));
        }
        
        exit( json_encode($data) );
    }
    
    /**
     * [AJAX]地图_获取<订单海量图>数据
     * http://apidev.cyb.cn/index.php?s=/statistics/map_hugemap_orders/
     * @author ^2_3^
     */
    public function map_hugemap_orders() {
        $start = microtime(true);
        $data['status'] = 0;
        $data['msg'] = 'init error';
        
        $start_date = I('request.start_date', '', 'trim');
        $end_date = I('request.end_date', '', 'trim');
        if( !IS_POST || empty($start_date) || empty($end_date) ) {
            $data['msg'] = 'no args';
            exit( json_encode($data) );
        }
        
        $start_time = strtotime( $start_date );
        $end_time = strtotime( $end_date ) + 86400;
        
        $sql = "
            -- 订单
            SELECT
            	oi.order_id,
            	oi.order_sn,
            	oi.wdr_id,
            	wdr.name AS wdr_name,
            	wdr.zoning_id,
            	zc.name AS zc_name,
            	oi.wp_userid,
            	oi.longitude,
            	oi.latitude
            FROM
            	sdx_order_info oi, 
                sdx_warehouse_deliver_region wdr, 
                sdx_zoning_cate zc
            WHERE
            	oi.wdr_id = wdr.id
            	AND wdr.zoning_id = zc.id
            	AND oi.longitude != ''
            	AND oi.latitude != ''
            	AND oi.confirm_time >= {$start_time}
            	AND oi.confirm_time < {$end_time}
            	AND oi.wp_userid != 0
            	AND oi.order_status IN (1, 5)
            	AND oi.pay_status IN (2, 3, 4)
            	AND oi.shipping_status = 2
        ";
        $data['sql'] = $sql;
        $list = M()->query( $sql );
        
        /// 区域
        $dis_mode_list = S('distribution_mode_data');
        if(!$dis_mode_list){
            $dis_mode_list = M("distribution_mode")->where(array("state"=>0))->select();
            if($dis_mode_list){
                S('distribution_mode_data',$dis_mode_list);
            }
        }
        
        if( !empty($list) ) {
            $o_list = array();
            foreach ( $list as $key=>$arr ){
//                 $o_list[ $arr['zoning_id'] ][] = array(
//                     'longitude' => $arr['longitude'],
//                     'latitude' => $arr['latitude']
//                 );
                $o_list[ $arr['zoning_id'] ][] = $arr;
            }
            
            $data['status'] = 1;
            $data['msg'] = 'ok';
            $data['o_list'] = $o_list;
            $data['dm_list'] = $dis_mode_list;
            
        }else {
            $data['msg'] = 'empty data';
        }
        
        $end = microtime(true);
        $time = $end - $start;
        $data['time'] = $time;
        exit( json_encode($data) );
    }
    
    /**
     * [AJAX]地图_获取<收货地址海量图>数据
     * http://apidev.cyb.cn/index.php?s=/Statistics/map_hugemap_data/
     * @author ^2_3^
     */
    public function map_hugemap_data() {
        $data['status'] = 0;
        $data['msg'] = 'error';
        
        $sql = "
            SELECT
            	ua.longitude,
            	ua.latitude,
            	COUNT(0) AS count_num
            FROM
            	sdx_user_address ua
            WHERE ua.longitude != '' AND ua.latitude != ''
            GROUP BY CONCAT(ua.longitude, '_', ua.latitude)
        ";
        $list = M()->query( $sql );
        
        if( !empty($list) ) {
            $data['huge_data'] = $list;
            $data['status'] = 1;
            $data['msg'] = "ok";
        }else {
            $data['msg'] = "empty data";
        }
        exit( json_encode($data) );
        
    }
    
    /**
     * 二维数组比较排序
     * *用例
     *  $this->cmp_fields = 'date';
     *  uasort($list_daily, "self::twodimension_arr_cmp");
     * @author ^2_3^
     */
    private function twodimension_arr_cmp( $childFirArr, $childSecArr ) {
        $fields_name = $this->cmp_fields;
        $fields_sort = $this->cmp_fields_sort;
// w_log('cyb_log', "{$fields_name}_{$fields_sort}");
        
        if( $childFirArr[$fields_name] == $childSecArr[$fields_name] ) {
            return 0;
        }
        if( strtolower($fields_sort) == 'desc' ) {
            return $childFirArr[$fields_name] > $childSecArr[$fields_name] ? -1 : 1;
    
        }else if( strtolower($fields_sort) == 'asc' ) {
            return $childFirArr[$fields_name] < $childSecArr[$fields_name] ? -1 : 1;
        }
    
    }
    
}